﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace NDF.XnaLibrary
{
	public static class Utilities
	{
		/// <summary>
		/// Determines whether the two vectors are equal withing the given margin of floating point error.
		/// </summary>
		/// <param name="vector1">Source vector.</param>
		/// <param name="vector2">Source vector.</param>
		/// <param name="floatingPointError">The margin of floating point error.</param>
		/// <returns>Returns true if the vector coordinates are almost equal.</returns>
		public static bool Vector3AlmostEqual(Vector3 vector1, Vector3 vector2, float floatingPointError)
		{
			bool isXEqual = Math.Abs(vector1.X - vector2.X) <= floatingPointError;
			bool isYEqual = Math.Abs(vector1.Y - vector2.Y) <= floatingPointError;
			bool isZEqual = Math.Abs(vector1.Z - vector2.Z) <= floatingPointError;

			bool areVectorsAlmostEqual = isXEqual && isYEqual && isZEqual;

			return areVectorsAlmostEqual;
		}

		/// <summary>
		/// Uses the given vector3 to find whether it exists in the current map. If so, sets its appropriate height.
		/// </summary>
		/// <param name="position">The position to check for.</param>
		/// <returns>The final position.</returns>
		internal static Vector3 GetPositionInMap(Vector3 position)
		{
			//Check whether the position vector is in map range. WARNING: The following code works only on maps 
			//in 1st quadrant (X and Z vertex coordinates are positive)
			if (position.X > Map.Current.TerrainLength || position.Z > Map.Current.TerrainWidth ||
				position.X < 0 || position.Z < 0)
				throw new ArgumentException("Invalid Position! X and Z must be positive and within map`s border!");

			int vertexIndex = (int)(Map.Current.MapUnitSize * (position.X + position.Z * Map.Current.TerrainLength));
			position.Y = Map.Current.Vertices[vertexIndex].Position.Y;
			return position;
		}
	}
}
